package com.example.zkweixiu.app.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.example.zkweixiu.app.broadcast.MyBroadcastReveicer;
import com.example.zkweixiu.app.broadcast.MyBroadcastReveicer2;
import com.example.zkweixiu.app.model.Imdata;
import com.example.zkweixiu.app.pro.PublicPro;
import com.littlegreens.netty.client.NettyTcpClient;
import com.littlegreens.netty.client.listener.MessageStateListener;
import com.littlegreens.netty.client.listener.NettyClientListener;

import org.greenrobot.eventbus.EventBus;
import org.joda.time.DateTime;
import org.litepal.LitePal;

import java.io.UnsupportedEncodingException;

public class MyService2 extends Service {
    public static NettyTcpClient mNettyTcpClient;
    private Imdata imdata;
    SQLiteDatabase db = LitePal.getDatabase();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.e("MyService", "服务启动");

        mNettyTcpClient = new NettyTcpClient.Builder()
                .setHost(PublicPro.SERVICE_TCP)    //设置服务端地址
                .setTcpPort(8192) //设置服务端端口号
                .setMaxReconnectTimes(5)    //设置最大重连次数
                .setReconnectIntervalTime(5)    //设置重连间隔时间。单位：秒
                .setSendheartBeat(true) //设置发送心跳
                .setHeartBeatInterval(30)    //设置心跳间隔时间。单位：秒
                .setHeartBeatData("00@#&_&%&") //设置心跳数据，可以是String类型，也可以是byte[]，以后设置的为准
                .setIndex(102)    //设置客户端标识.(因为可能存在多个tcp连接)
                .build();

        mNettyTcpClient.connect();

        mNettyTcpClient.setListener(new NettyClientListener() { //注册监听事件
            @Override
            public void onMessageResponseClient(Object msg, int index) {
                String ponse = msg.toString();
              // Log.e("onMessageResponseClient", ponse);


                    if (ponse.contains("A1")) {

                    } else if (ponse.contains("MSG_IM@_@%#")){
                        if (PublicPro.userBean == null) {
                            return;
                        }
                        Log.e("CLI_SET",ponse);
                        String[] split = ponse.split("@_@%#",6);

                        Log.e("onMessageResponseClient", split[3]);


                        if (split[3].equals(PublicPro.userBean.getData().getGuaUuid())) {
                            return;
                        }
                        long millis = new DateTime().getMillis(); //获取当前系统时间戳
                        imdata = new Imdata();
                        imdata.setMy_uuid(PublicPro.userBean.getData().getGuaUuid());
                        imdata.setIs_send("2");
                        imdata.setIm_img(split[1]);
                        imdata.setIm_name(split[2]);
                        imdata.setIm_uuid(split[3]);
                        imdata.setIm_msg(split[4]);
                        imdata.setIm_time(millis);
                        imdata.save();
                        PublicPro.MSG_COUNT++;
                        PublicPro.NEWS_MSG = imdata;
                        EventBus.getDefault().post(imdata);
                    }
/*                    else if ("200".equals(ponse)){
                        EventBus.getDefault().post(ponse);
                    }*/

            }

            @Override
            public void onClientStatusConnectChanged(int statusCode, int index) {
                Log.e("setListener", String.valueOf(statusCode));
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        if (mNettyTcpClient != null) {
            if (!mNettyTcpClient.getConnectStatus()) {//没有连接 连接
                mNettyTcpClient.connect();

            }
        }



        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent2 = new Intent(this, MyBroadcastReveicer2.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent2, 0);
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 * 2, pendingIntent);
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }


    private synchronized void sendService() {


    }


}
